import Vue from "vue";
import MenuList from "@/components/MenuList/index.vue";

export default class Menu {
  constructor(targetEl, list, callback) {
    this.targetEl = targetEl;
    this.targetElDom = document.querySelector(this.targetEl);
    this.menuEl = null;
    this.list = list;
    this.callback = callback || (() => {
    });
    this.idStr = Math.ceil(Math.random() * 100000);
    // this.props = props;
    this.init();
  }

  show(e) {
    const el = document.createElement("div");
    el.setAttribute("id", "menuContainer");
    const targetElDom = document.querySelector(this.targetEl);
    targetElDom.appendChild(el);

    let style = {
      position: "absolute",
      top:
        e.clientY +
        this.targetElDom.scrollTop -
        this.targetElDom.offsetTop +
        "px",
      left: e.clientX - this.targetElDom.offsetLeft + "px"
    };

    this.menuEl = new Vue({
      render: (h) => (
        <MenuList
          style={style}
          onClick={this.callback && this.callback}
          data={this.list}
          idStr={this.idStr}
        ></MenuList>
      )
    });
    this.menuEl.$mount("#menuContainer");
    this.menuEl.$nextTick(() => {
      const menu = document.getElementById("menu" + this.idStr);
      const menuParent = menu.parentElement;
      const domConfig = menu.getBoundingClientRect();
      if (domConfig.left < menuParent.offsetLeft) {
        style.left = "0px";
      }
      if (domConfig.right > menuParent.clientWidth + menuParent.offsetLeft) {
        style.left = menuParent.clientWidth - domConfig.width + "px";
        // style.right = menuParent.offsetWidth + menuParent.offsetLeft + "px";
      }
      if (domConfig.top < 0) {
        style.top = "0px";
      }
      if (domConfig.bottom > menuParent.offsetTop + menuParent.clientHeight) {
        style.top = menuParent.clientHeight + menuParent.scrollTop - domConfig.height + "px";
      }
      Object.keys(style).forEach((key) => {
        menu.style[key] = style[key];
      });
    });
  }

  remove() {
    if (this.menuEl) {
      this.menuEl.$destroy();
      this.menuEl.$el.remove();
    }
    this.menuEl = null;
  }

  destory() {
    this.targetElDom = null;
    this.menuEl = null;
  }

  init() {
    // console.log(this.props);
    this.targetElDom.addEventListener("contextmenu", (e) => {
      e.preventDefault();
      e.stopPropagation();
      this.remove();
      this.show(e);
    });
    document.addEventListener("click", (e) => {
      this.remove();
    });
  }
}
